<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  .weui-cells__title {
    text-align: left;
  }
  .oitem {
    padding: 3px;
  }
  .hide {
    display: none;
  }
  .acts {
    font-size: 0;
  }
  .acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
  }
  .outstore >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .outstore >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
  .weui-cell.fir {
    border-top: 0;
  }
  .weui_uploader_input_wrp.inrow {
    width: 30px;
    height: 30px;
    margin: 0;
  }
  .weui_uploader_input_wrp:before {
    height: 19.5px;
  }
  .weui_uploader_input_wrp:after {
    width: 19.5px;
  }
  .weui-uploader_file.inrow {
    margin: 0;
    width: 40px;
  }
</style>
<template>
  <div class="outstore">
    <div class="rj-wrap">
      销售出库
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form method="post" id="formid">
        <input type="hidden" name="entity.loadcount" ref="entlcount">
        <input class="weui-input" type="hidden" name="entity.lbweight" :value="totalRealWei">
        <div class="weui-cell">
          <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="text" name="" readonly="true" :value="sellform.storeroomname">
          </div>
        </div>
        <div class="weui-cell" style="padding: 10px 15px;">
          <div class="weui-cell__hd"><label for="" class="weui-label">库存组织</label></div>
          <div class="weui-cell__bd">
            <input class="weui-input" type="hidden" name="entity.orgguid" readonly="true" :value="sellform.storerOrgguid">
            <input class="weui-input" type="text" name="" readonly="true" :value="sellform.orgName">
            <!--            <select class="weui-select" name="entity.orgguid" v-model="orgguid" ref="orgguid" disabled="disabled">-->
            <!--              <option value="0" style="color: #ccc;">请选择所属公司</option>-->
            <!--              <option  v-for="(org, i) in orgs" :key="org.guid" :value="org.guid" :selected="org.guid==sellform.storerOrgguid">{{org.name}}</option>-->
            <!--            </select>-->
          </div>
        </div>
        <div class="weui-cell">
          <div class="weui-cell__hd"><label for="" class="weui-label">出库类型</label></div>
          <div class="weui-cell__bd">
            <select class="weui-select minSelect" style="" name="" v-model="picktype" disabled>
              <option v-for="(item, index) in productTypes" :value="item.dictkey" >{{item.dicttext}}</option>
            </select>
            <!--            <input class="weui-input" type="text" name="" readonly="true" :value="sellform.quitSRType == 1 ? '原材料库' : '产成品库'">-->
          </div>
        </div>
<!--        <div class="weui-cell">-->
<!--          <div class="weui-cell__hd"><label class="weui-label">净重(吨)</label></div>-->
<!--          <div class="weui-cell__bd">-->
<!--            <input class="weui-input" type="text" name="" readonly="true" v-model="totalRealWei">-->
<!--          </div>-->
<!--        </div>-->
        <div class="weui-cell" v-if="orderfiles.length > 0">
          <div class="weui-cell__hd"><label class="weui-label">附件</label></div>
          <div class="weui-cell__bd">
            <a v-for="(item, index) in orderfiles" :href="item.url">
              <input class="weui-input" type="text" name="" :value="item.filename">
            </a>
            <!--              <input class="weui-input" type="text" name="" :value="baseInfo.createtime">-->
          </div>
        </div>
<!--        <div class="oitem pack" v-for="(pack, packindex) in spitems" :key="pack.guid" :hidden="hasPitemDeled(packindex)">-->
        <div class="oitem pack" v-for="(pack, packindex) in spitems" :key="pack.guid">
          <div class="weui-cells__title">货品明细 {{packindex + 1}}
            <p class="acts" style="float: right;color: #1aad19;">
<!--              <span @click="copyItem(index)" style="padding-right: 5px;">新增</span>-->
<!--              <span v-if="sellform.items.length > 1">|</span>-->
              <span @click="expendPerm(packindex, 'pack')" >换库房</span>
              <span style="padding: 0 3px;" v-if="totalItemsLen > 1">|</span>
              <span @click="delPackItem(packindex)" v-if="totalItemsLen > 1">删除</span>
            </p>
          </div>
          <div class="weui-panel weui-panel_access fir" style="text-align: left;margin-top: 0;">
            <div class="weui-panel__hd" style="font-weight: 600;color: #333;font-size: 14px;">{{pack.productname}} {{pack.spname}}</div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label" style="width: 80px;">订单数量</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input inlinput1" type="text" name="" readonly="true" :value="pack.orderpack">
                <input class="weui-input inlinput2" type="text" readonly :value="pack.unit">
              </div>
              <template v-if="sellform.settletype == 1">
                <div class="weui-cell__hd"><label class="weui-label" style="width: 50px;">赠送</label></div>
                <div class="weui-cell__bd">
                  <input class="weui-input givecount inlinput1" type="number" readonly :value="pack.handselcount">
                  <input class="weui-input inlinput2" type="text" readonly :value="pack.unit">
                </div>
              </template>
            </div>
<!--            <div class="weui-cell">-->
<!--              <div class="weui-cell__hd"><label class="weui-label">赠送数量</label></div>-->
<!--              <div class="weui-cell__bd">-->
<!--                <input class="weui-input givecount" style="width: 55%;display: inline-block;" type="number" readonly :value="pack.handselcount">-->
<!--                <input class="weui-input" style="width: 40%;display: inline-block;" type="text" readonly :value="pack.unit">-->
<!--              </div>-->
<!--            </div>-->
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">出库数量</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input packOutcount" :data-index="packindex" style="width: 80%;display: inline-block;" type="number" placeholder="订单数量+赠送数量">
                <input class="weui-input" style="width: 15%;display: inline-block;" type="text" readonly :value="pack.unit">
              </div>
            </div>
            <div class="weui-panel__bd" style="padding-left: 15px;">
              <div v-for="(product, index) in pack.sellitems" class="weui-panel weui-panel_access" style="text-align: left;margin-top: 0;">
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].handsel'" :value="pack.handselcount">
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].srguid'" :value="sellform.storermguid" :disabled="canEditRoom(addBasc3(packindex, index))" :data-index="addBasc3(packindex, index)" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].productguid'" :value="product.productguid" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].productname'" :value="product.productname" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].spguid'" :value="product.spguid" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].rawspguid'" :value="product.spguid" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].price'" :value="product.price" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].orderItemGuid'" :value="product.guid" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].packweight'" :value="product.packweightitem" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].whinunit'" :value="product.whinunit" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].packamount'" :value="product.packamount" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].stockunit'" :value="product.stockunit" />
                <input type="hidden" :name="'items[' + addBasc3(packindex, index) + '].sfunitid'" :value="product.sfunitid" />
                <div class="weui-panel__hd">
                  <span style="display: inline-block;width: 70%;color: #333;">{{product.productname}} {{product.spname}}</span>
<!--                  <input class="weui-input outcount" style="display: inline-block;width: 8%;" type="number" readonly :data-index="index" :data-unit="product.packweightitem" :data-netweight="product.netweight" :data-whinunit="product.whinunitName" :data-packamount="product.packamount" :name="'items[' + addBasc3(packindex, index) + '].loadcount'" >-->
                  <input class="weui-input outcount" style="display: inline-block;width: 8%;" type="number" readonly :data-index="index" :data-unit="product.packweightitem" :data-netweight="product.netweight" :data-whinunit="product.whinunitName" :data-packamount="product.packamount" :name="'items[' + addBasc3(packindex, index) + '].loadcount'">
                  <span>{{product.unit}}</span>
                </div>
                <div class="weui-panel__bd">
                  <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg" style="padding: 0;">
                    <div class="weui-media-box__bd">
                      <div class="weui-media-box__desc">
                        <div class="weui-cell" style="padding: 0 15px;">
                          <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
                          <select class="weui-select room" :name="'items[' + addBasc3(packindex, index) + '].srguid'" :ref="packIt3('roomid', packindex, index)" :data-index="addBasc3(packindex, index)" :disabled="!canEditRoom(addBasc3(packindex, index))">
                            <option :value="sellform.storermguid">{{sellform.storeroomname}}</option>
                            <option v-for="(item, i) in rooms" :key="item.srguid" :value="item.srguid">{{item.storeName}}</option>
                          </select>
                        </div>
                      </div>
                    </div>
                  </a>
                </div>
                <div class="weui-panel__bd">
                  <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg" style="padding: 0;">
                    <div class="weui-media-box__bd">
                      <div class="weui-media-box__desc">
                        <div class="weui-cell" style="padding: 0 15px;">
                          <div class="weui-cell__hd"><label class="weui-label">库间</label></div>
                          <select class="weui-select houseroom" :name="'items[' + addBasc3(packindex, index) + '].shrguid'" >
                            <option value="0">请选择库间</option>
                            <option v-for="(hou, i) in autoHouses(addBasc3(packindex, index))" :key="hou.storeroomguid" :value="hou.storeroomguid">{{hou.storeroomName}} &nbsp; ({{hou.storeqty}} {{hou.stockunit}})</option>
                          </select>
                        </div>
                      </div>
                    </div>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
<!--        <div class="oitem2 oitem" v-for="(product, index) in sellform.items" :key="product.guid" :hidden="hasItemDeled(index)">-->
        <div class="oitem2 oitem" v-for="(product, index) in sellform.items" :key="product.guid">
          <input type="hidden" :name="'items[' + addBasc(index) + '].handsel'" :value="product.handselcount" />
          <input type="hidden" :name="'items[' + addBasc(index) + '].srguid'"  :value="sellform.storermguid" :disabled="canEditRoom(addBasc(index))"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].productguid'" :ref="packIt('productguid', index)"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].productname'" :ref="packIt('productname', index)"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].spguid'" :ref="packIt('spguid', index)"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].rawspguid'" :ref="packIt('rawspguid', index)"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].spename'" :ref="packIt('spename', index)"/>
          <input type="hidden" :name="'items[' + addBasc(index) + '].stockunit'" :ref="packIt('stockunit', index)" />
          <input type="hidden" :name="'items[' + addBasc(index) + '].sfunitid'" :ref="packIt('sfunitid', index)" />
          <input type="hidden" :name="'items[' + addBasc(index) + '].price'" :value="product.price" />
          <input type="hidden" :name="'items[' + addBasc(index) + '].orderItemGuid'" :value="product.guid" />
          <input type="hidden" :name="'items[' + addBasc(index) + '].packweight'" :value="product.packweightitem" />
          <div class="weui-cells__title">货品明细 {{addBasc2(index) + 1}}
            <p class="acts" style="float: right;color: #1aad19;">
<!--              <span @click="copyItem(index)" style="padding-right: 5px;">新增</span>-->
              <span @click="editItem(product.spguid, index)">改规格</span>
              <span style="padding: 0 3px;">|</span>
              <span @click="expendPerm(addBasc(index))">换库房</span>
              <span style="padding: 0 3px;" v-if="totalItemsLen > 1">|</span>
              <span @click="delItem(index)" v-if="totalItemsLen > 1">删除</span>
            </p>
          </div>
          <div class="weui-cell fir">
<!--            <div class="weui-cell__hd"><label class="weui-label">产品</label></div>-->
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" style="font-weight: 600;color: #333;font-size: 14px;" name="" readonly="true" :ref="packIt('prospec', index)">
            </div>
          </div>
<!--          <div class="weui-cell">-->
<!--            <div class="weui-cell__hd"><label class="weui-label">规格</label></div>-->
<!--            <div class="weui-cell__bd">-->
<!--              <input class="weui-input" type="text" name="" readonly="true" :value="product.spname">-->
<!--            </div>-->
<!--          </div>-->
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">库房</label></div>
            <div class="weui-cell__bd">
              <select class="weui-select minSelect room" :name="'items[' + addBasc(index) + '].srguid'" :ref="packIt('roomid', index)" :data-index="addBasc(index)" :disabled="!canEditRoom(addBasc(index))">
                <option :value="sellform.storermguid">{{sellform.storeroomname}}</option>
                <option v-for="(item, i) in rooms" :key="item.srguid" :value="item.srguid">{{item.storeName}}</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label for="" class="weui-label">库间</label></div>
            <div class="weui-cell__bd">
              <!--              <input class="weui-input shrguid" :id="'shrguid' + addBasc(index)" type="text" name="" placeholder="请选择库间">-->
              <!--              <input type="hidden" :id="'shrid' + addBasc(index)" name="items[0].shrguid">-->
              <select class="weui-select houseroom" :name="'items[' + addBasc(index) + '].shrguid'" >
                <option value="0">请选择库间</option>
                <option v-for="(hou, i) in autoHouses(addBasc(index))" :value="hou.storeroomguid">{{hou.storeroomName}} &nbsp; ({{hou.storeqty}} {{hou.stockunit}})</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label" style="width: 80px;">订单数量</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" style="width: 50%;display: inline-block;" type="text" name="" readonly="true" :value="product.orderpack">
              <input class="weui-input" style="width: 30%;display: inline-block;" type="text" readonly :value="product.unit">
            </div>
            <template v-if="sellform.settletype == 1">
              <div class="weui-cell__hd"><label class="weui-label" style="width: 50px;">赠送</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input givecount" style="width: 50%;display: inline-block;" type="number" readonly :value="product.handselcount">
                <input class="weui-input" style="width: 30%;display: inline-block;" type="text" readonly :value="product.unit">
              </div>
            </template>
          </div>
            <div class="weui-cell">
              <div class="weui-cell__hd"><label class="weui-label">出库数量</label></div>
              <div class="weui-cell__bd">
                <input class="weui-input outcount" style="width: 80%;display: inline-block;" :data-index="index" :data-unit="product.netweight" type="number" pattern="[0-9]*" :name="'items[' + addBasc(index) + '].loadcount'" placeholder="订单数量+赠送数量" :ref="packIt('outcount', index)">
                <input class="weui-input" style="width: 15%;display: inline-block;" type="text" readonly :value="product.unit">
              </div>
            </div>
<!--            <div class="weui-cell">-->
<!--              <div class="weui-cell__hd"><label class="weui-label">净重(吨)</label></div>-->
<!--              <div class="weui-cell__bd">-->
<!--                <input class="weui-input weight" type="number" :name="'items[' + addBasc(index) + '].weight'" :readonly="product.netweight != undefined && product.netweight != ''">-->
<!--              </div>-->
<!--            </div>-->
        </div>
<!--        <p v-show="conditionSR" class="help" @click="expendPerm">跨库房出库？</p>-->
        <div ref="actHtml" class="fixcont">
          <div class="weui-cells weui-cells_form">
            <div class="weui-cell">
              <div class="weui-cell__bd">
                <textarea class="weui-textarea" id="remark" name="entity.remark" placeholder="请输备注内容" rows="2"></textarea>
              </div>
            </div>
          </div>
          <div class="weui_cell">
            <div class="weui_cell_bd weui_cell_primary">
              <div class="weui_uploader">
                <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                  <div class="weui_cell_bd weui_cell_primary" id="outstore">出库单上传</div>
                  <div class="weui_cell_ft" id=""></div>
                </div>
                <div class="weui_uploader_bd">
                  <ul class="weui-uploader_files" id="images">
                    <li class="weui-uploader_file" v-for="(img, index) in images1.serverId" :id="img"  @click=del(img,1) ><img :src="images1.srcStr[index]" width="85" /></li>
                  </ul>
                  <div class="weui_uploader_input_wrp">
                    <input type="button" id="selectImage"  class="weui_uploader_input" >
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary halfbtn subbtn" href="javascript:" @click="postForm">出库</a>
            <a class="weui-btn weui-btn_primary halfbtn subbtn" v-if="refuseflag == 1" href="javascript:" @click="rejectIt">拒绝</a>
            <a class="weui-btn weui-btn_primary halfbtn" v-else  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
          </div>
        </div>
      </form>
    </div>
    <div id="bmlogs">
      <SalesOperationLogs2 :nodeid="nodeid" :orderid="id" :srguid="sellform.storermguid" :departid="sellform.depguid"></SalesOperationLogs2>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  import SalesOperationLogs2 from '../common/SalesOperationLogs2'
  import qs from 'qs';

  export default {
    name: 'OutStoreRoom2',
    data () {
      return {
        openid: localStorage.openid,
        id: '',
        nodeid: '',
        annex: '',
        sellform: {},
        orgs: [],
        rooms: [],
        strmid: '',
        houses: [],
        dict:[],
        wxParams: {},
        status: '',
        quitSRType: '',
        orgguid: 0,
        orgname: '',
        // canEditRoom: false,
        conditionSR: false,
        picktype: 2,
        images1: {
          serverId: [],
          srcStr: [],
        },
        images2: {
          serverId: [],
          srcStr: [],
          weight: []
        },
        discountRate:{},
        totalPackWei: 0,
        productTypes: [],
        lbweight: '',
        totalRealWei: 0,
        refuseflag: '',
        refuseNodes: [],
        orderfiles: [],
        spitems: '',
        totalPackitemLen: 0,
        totalItemsLen: 0,
        delPItemIndexs: [],
        delItemIndexs: [],
        artoken: '',
        editRoomIndexs: [],
        mergeSpitems: []
      }
    },
    components: {
      SalesOperationLogs2
    },
    mounted () {
      console.log('mounted')
      //根据userid和时间戳生成唯一字符串
      this.artoken = this.createToken();
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight);

      let that = this;
      this.id = this.$route.query.guid;
      this.nodeid = this.$route.query.nodeid;
      this.annex = this.$route.query.annex;
      this.refuseflag = this.$route.query.refuseflag;
      this.getOrder(this.id, this);
      this.getProducttypes();
      // this.conditionSR = this.$route.query.conditionSR == 'true';
      if (this.$route.query.status) {
        this.status = this.$route.query.status;
      }

      this.getRefuseNodes();

      $('#formid').on('change', '.room', function () {
        let index = $(this).data('index');
        console.log('index:', index)
        console.log('totalPackitemLen:', that.totalPackitemLen)
        if (index < that.totalPackitemLen) {
          that.getPLInfo(index, that.orgguid, that.mergeSpitems[index].productguid, that.mergeSpitems[index].spguid);
        } else {
          let ii = index - that.totalPackitemLen;
          that.getPLInfo(index, that.orgguid, that.sellform.items[ii].productguid, that.sellform.items[ii].spguid);
        }
      })

      $('.weui-panel').on('click', '.uploaderFiles .attachimg', function () {
        var num = $(this).parent().children().not( ".exp" ).length;
        var imgArr = [];
        for (var i=0; i<num; i++) {
          imgArr.push($(this).parent().find('.attachimg').eq(i).data('img'));
        }
        var pnum = $(this).parent().find('.exp').length;
        var index = pnum > 0 ? $(this).index() - pnum : $(this).index();
        var pb = $.photoBrowser({
          items: imgArr,
          initIndex: index
        });
        pb.open();
      });
      //监听出库件数计算当前明细包装重量、净重
      $('#formid').on('change', '.packOutcount', function () {

        let elem = $(this);
        let index = $(this).data('index');
        //不允许录入小数
        if (elem.val().indexOf('\.') > -1) {
          elem.val('');
          return false;
        }
        if (elem.val() > that.spitems[index].orderpack + that.spitems[index].handselcount) {
          elem.val('');
          that.toastText('出库数量不能大于 订单数量+赠送数量！');
          return false;
        }

        let packOutcount = $(this).val();
        let outcountElem = $(this).parents('.oitem').find('.outcount');
        console.log('outcountElem:', outcountElem.length)
        for (let i=0; i<outcountElem.length; i++) {
          let packamount = outcountElem.eq(i).data('packamount');
          console.log('packamount:', packamount)
          outcountElem.eq(i).val(packamount * packOutcount);
          //净重、包装重量赋值
          that.computeItemWei(outcountElem.eq(i));
        }
        //监听明细净重计算总净重
        that.computeAllWei();
        //计算总的出库数量
        that.computeLcount();
      })
      //监听出库件数计算当前明细重量
      $('#formid').on('keyup', '.oitem2 .outcount', function () {
        let index = $(this).data('index');
        if ($(this).val().indexOf('\.') > -1) {
          $(this).val('');
        }
        if ($(this).val() > that.sellform.items[index].orderpack + that.sellform.items[index].handselcount) {
          $(this).val('');
          that.toastText('出库数量不能大于 订单数量+赠送数量！');
        }

        //计算总的出库数量
        that.computeLcount();

        //计算明细重量
        that.getLastWei(index);
        //监听明细净重计算总净重
        that.computeAllWei();

      })
      this.getFiles();

    },
    activated() {
      console.log('activated')
    },
    watch: {
      'picktype': function (val) {
        this.picktype = val;
        // for(let i=0; i<this.sellform.items.length; i++) {
        //   this.getPLInfo(i, this.orgguid, this.sellform.items[i].productguid, this.sellform.items[i].spguid);
        // }
        this.getMutilHouse();
      },
      //只有一条货品明细的情况下，明细净重直接取计算得到的货品总净重填入
      // 'totalRealWei': function (val) {
      //   if (this.sellform.items.length == 1) {
      //     if (this.sellform.settletype == 1) {
      //       $('.weight').eq(0).val(val);
      //     } else {
      //       $('.outweight').eq(0).val(val);
      //     }
      //   }
      // }
    },
    methods: {
      packIt: function(str, index) {
        return str + this.addBasc(index);
      },
      packIt3: function(str, packindex, index) {
        return str + this.addBasc3(packindex, index);
      },
      computeAllWei: function() {
        let that = this;
        let totalRealWei = 0;
        let elemWei = $('.weight:not(:hidden)');
        for (let i=0; i<elemWei.length; i++) {
          let iwei = elemWei.eq(i).val() == '' ? 0 : parseFloat(elemWei.eq(i).val());
          totalRealWei += parseFloat(iwei);
        }
        that.totalRealWei = that.toFix6(totalRealWei);
      },
      computeLcount: function() {
        let count = 0;
        let elemPIcount = $('.packOutcount:not(:hidden)');
        for (let i=0; i<elemPIcount.length; i++) {
          let icount = elemPIcount.eq(i).val() == '' ? 0 : parseInt(elemPIcount.eq(i).val());
          count += icount;
        }
        let elemIcount = $('.oitem2').find('.outcount:not(:hidden)');
        for (let i=0; i<elemIcount.length; i++) {
          let icount = elemIcount.eq(i).val() == '' ? 0 : parseInt(elemIcount.eq(i).val());
          count += icount;
        }
        this.$refs.entlcount.value = count;
      },
      getMutilHouse: function(orgid = '') {
        //套装货品明细
        this.spitems.filter((item, packindex) =>{
          item.sellitems.filter((pro, index) => {
            this.getPLInfo(this.addBasc3(packindex, index), orgid, this.spitems[packindex].sellitems[index].productguid, this.spitems[packindex].sellitems[index].spguid);
          })
        })
        //非套装货品明细
        for(let i=0; i<this.sellform.items.length; i++) {
          this.getPLInfo(this.totalPackitemLen + i, orgid, this.$refs[this.packIt('productguid', i)][0].value, this.$refs[this.packIt('spguid', i)][0].value);
        }
      },
      addBasc: function(index) {
        return this.totalPackitemLen + parseInt(index);
      },
      addBasc2: function(index) {
        return this.spitems.length + parseInt(index);
      },
      addBasc3: function(packindex, index) {
        let no = 0;
        for (let i=0; i<packindex; i++) {
          no += this.spitems[i].sellitems.length;
        }
        return no + parseInt(index);
      },
      computeItemWei: function(elem) {
        let that = this;
        let index = elem.data('index');
        let thisElem = elem;
        let whinunit = elem.data('whinunit');  //库存重量单位
        //计算包装重量
        let unitWei = parseFloat(thisElem.data('netweight') / 1000);
        // let unitWei = whinunit == 1 ?  parseFloat(thisElem.data('unit') / 1000) : parseFloat(thisElem.data('unit'));
        let currrCount = parseInt(elem.val());
        $('.packwei').eq(index).val(that.toFix6(currrCount * unitWei));

        //that.getTotalPackWei();

        //计算明细净重
        if (elem.data('netweight') != '' && parseFloat(elem.data('netweight')) > 0) {
          // let netWei = whinunit == 1 ?  parseFloat(thisElem.data('netweight') / 1000) : parseFloat(thisElem.data('netweight'));
          let netWei = parseFloat(thisElem.data('netweight') / 1000);

          let itemWei = that.toFix6(parseInt(elem.val()) * netWei);
          console.log('thisElem.data(\'netweight\'):', thisElem.data('netweight'))
          console.log('computeItemWei index:', index)

          console.log('itemWei:', itemWei)

          thisElem.parents('.oitem').find('.weight').eq(index).val(itemWei);
        }
      },
      getFiles: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Fileinfo!getFileinfo.action',
          params: {orderid: this.id}
        }).then(response => {

          if (response.data.msg == 'success') {
            this.orderfiles = response.data.files;
          } else {
            //失败时不提示
          }
        });
      },
      autoHouses: function(no) {
        return this.houses['house' + no];
      },
      expendPerm: function(index, type = '') {
        if (type == 'pack') {
          const start = this.addBasc3(index, 0);
          const count = this.spitems[index].sellitems.length;
          for (let i=start; i<start + count; i++) {
            this.editRoomIndexs.push(i);
          }
          console.log('this.editRoomIndexs:', this.editRoomIndexs)
        } else {
          this.editRoomIndexs.push(index);
        }
        // this.canEditRoom = true;
      },
      canEditRoom: function(index) {
        return this.editRoomIndexs.indexOf(index) > -1;
      },
      copyItem: function(index) {
        this.sellform.items.splice(index, 0, this.sellform.items[index]);
        //更新新增items的库间
        this['house' + (index + 1)] = this['house' + index];
      },
      delPackItem: function(index) {
        let that = this;
        $.confirm('确定要删除该明细？', function () {
          // $('.pack').eq(index).find('.outcount').val(0);
          // $('.pack').eq(index).find('.weight').val(0);
          // that.delPItemIndexs.push(index);
          that.spitems = that.spitems.filter((item, i) => {
            return i != index;
          });
          that.$nextTick(function () {
            that.getMutilHouse();
            //计算总的出库数量
            that.computeLcount();
            //监听明细净重计算总净重
            that.computeAllWei();
          })
          // that.totalItemsLen = that.spitems.length - that.delPItemIndexs.length + that.sellform.items.length - that.delItemIndexs.length;
          that.totalItemsLen = that.spitems.length + that.sellform.items.length;
        })
      },
      editItem: function(id, index) {
        let that = this;
        let currId = that.$refs[that.packIt('spguid', index)][0].value;

        this.axios({
          method: 'get',
          url: '/sales/Interchangespec!getChangeSpecs.action',
          params: {itemspecguid: currId}
        }).then(response => {
          if (response.data.msg == 'success') {
            if (response.data.result && response.data.result.length <= 0) {
              this.toastText('没有可更换的规格');
              return;
            }
            let actions = response.data.result.map((item, i) =>{
              return {
                text: item.productname + ' ' + item.specname,
                onClick: () => {
                  $.confirm("确定要更换产品？", function() {
                    that.replaceSpec(item, index);
                    //非套装货品明细重新获取库间
                      that.getPLInfo(that.addBasc(index), that.orgguid, item.prodguid, item.specguid);
                  })
                }
              }
            })
            $.actions({
              title: '选择要更换的产品',
              actions: actions
            });
          }
        })
      },
      replaceSpec: function(item, index) {
        let that = this;
        that.$refs[that.packIt('productguid', index)][0].value = item.prodguid || item.productguid;
        that.$refs[that.packIt('productname', index)][0].value = item.productname;
        that.$refs[that.packIt('spguid', index)][0].value = item.specguid || item.spguid;
        that.$refs[that.packIt('rawspguid', index)][0].value = item.specguid || item.spguid;
        that.$refs[that.packIt('spename', index)][0].value = item.specname || item.spname;
        that.$refs[that.packIt('stockunit', index)][0].value = item.stockunit;
        that.$refs[that.packIt('sfunitid', index)][0].value = item.sfunitid;
        if (item.specname) {
          that.$refs[that.packIt('prospec', index)][0].value = item.productname + ' ' + item.specname;
        } else if (item.spname) {
          that.$refs[that.packIt('prospec', index)][0].value = item.productname + ' ' + item.spname;
        }

        if (that.$refs[that.packIt('outcount', index)] != undefined && that.$refs[that.packIt('outcount', index)] != 'undefined') {
          that.$refs[that.packIt('outcount', index)][0].setAttribute("data-unit", item.netweight);

          //计算明细重量
          that.getLastWei(index);
          //计算总净重
          that.computeAllWei();
        }
      },
      getLastWei: function(index) {
        let that = this;
        let thisval = that.$refs[that.packIt('outcount', index)][0].value;
        let unit = that.$refs[that.packIt('outcount', index)][0].getAttribute('data-unit');

        let unitWei = parseFloat(unit) / 1000;
        let currrCount = parseInt(thisval);
        $('.oitem2 .weight').eq(index).val(that.toFix6(currrCount * unitWei));
      },
      delItem: function(index) {
        let that = this;
        $.confirm('确定要删除该明细？', function () {
          // $('.oitem2').eq(index).find('.outcount').val(0);
          // $('.oitem2').eq(index).find('.weight').val(0);
          // that.delItemIndexs.push(index);
          that.sellform.items = that.sellform.items.filter((item, i) => {
            return i != index;
          });
          that.$nextTick(function () {
            that.getMutilHouse();
            //计算总的出库数量
            that.computeLcount();
            //监听明细净重计算总净重
            that.computeAllWei();
          })
          // that.totalItemsLen = that.spitems.length - that.delPItemIndexs.length + that.sellform.items.length - that.delItemIndexs.length;
          that.totalItemsLen = that.spitems.length + that.sellform.items.length;
        })
      },
      getRooms: function() {
        this.axios({
          method: 'get',
          // url: '/sales/Whoutform!getSrByPermis.action',
          url: '/sales/Whoutform!getSrbyWh.action',
          params: {permis: 4, srguid: this.sellform.storermguid}
        }).then(response => {
          if (response.data.status == 'true') {
            // this.rooms = response.data.srs.filter(this.removeCurrentRoom);
            this.rooms = response.data.result;
          } else if (response.data.status == 'false') {
            this.toastText(response.data.result);
          } else {
            this.toastError('系统错误');
          }
        });
      },
      removeCurrentRoom: function(item) {
        return item.guid != this.sellform.storermguid;
      },
      wxConfig: function(wxParams) {
        wx.config({
          debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: wxParams.appid,    // 必填，公众号的唯一标识
          timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
          nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
          signature: wxParams.signature,// 必填，签名
          jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
        });
      },
      wxUoloadImage: function(that) {
        let cthis = this;
        //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images1.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images1.srcStr.push(n);
                        })
                      }

                      cthis.images1.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        //});

      },
      del: function (id, index){
        let cthis = this;
        $.actions({
          actions: [{
            text: "删除",
            onClick: function() {
              $.confirm("确定删除?", function() {
                //点击确认后的回调函数
                //删掉id
                var ids = cthis['images' + index].serverId;
                var a =  ids.indexOf(id);
                cthis.$nextTick(function () {
                  cthis['images' + index].serverId.splice(a,1);
                  cthis['images' + index].srcStr.splice(a,1);
                })
              }, function() {
                //点击取消后的回调函数
              });
            }
          }
          ]
        });
      },
      checkCore:function() {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
        if (isIOS) {
          return 'ios';
        } else  {
          return 'android';
        }
      },
      getOrg: function() {
        //获取明细产品/规格
        let productids = '';
        let spguids = '';
        this.sellform.items.forEach(item => {
          productids += item.productguid + ','
          spguids += item.spguid + ','
        })

        productids = productids.substring(0,productids.length-1)
        spguids = spguids.substring(0,spguids.length-1)

        this.axios({
          method: 'get',
          // url: '/sales/Whoutform!getOrg.action',
          url: '/sales/Whoutform!getOrgbyPro.action',
          params: {storermguid: this.sellform.storermguid, productids: productids, spguids: spguids}
        }).then(response => {
          if (response.data.orgs != undefined) {
            this.orgs = response.data.orgs;
            // if (response.data.orgs.length > 0) {
            //   this.orgguid = response.data.orgs[0].guid;
            // }
          }
        });
      },
      getProducttypes: function() {
        let that = this;
        this.axios({
          method: 'get',
          responseType: 'json',
          url: '/sales/Sellform!findDict.action',
          params: {type: 91}
        }).then(response => {
          if (response.statusText == "OK") {
            that.productTypes = response.data;
          } else {
            this.toastText('获取货品类型数据失败');
          }
        });
      },
      getPLInfo: function(index, orgguid, productid, spguid) {
        const roomid = this.$refs['roomid' + index][0].value;
        this.axios({
          method: 'get',
          url: '/sales/Whoutform!getPLInfo.action',
          // params: {orgid: orgguid, strmid: this.sellform.storermguid, picktype: this.picktype, productid: productid, spec: spguid}
          params: {strmid: roomid, picktype: this.picktype, productid: productid, spec: spguid}
        }).then(response => {
          if (response.data.houses != undefined) {
            let houseitem = 'house' + index;
            this.$set(this.houses, houseitem, response.data.houses);
            //this[houseitem] = response.data.houses;
          }
        });
      },
      getOrder: function(id, that) {
        let hthis = this;
        this.axios({
          method: 'post',
          url: '/sales/Whoutform!saleOutForm.action',
          params: {orderid: id, url: location.href.split("#")[0]}
        }).then(response => {
          if (response.status == 200) {
            this.sellform = response.data.saleform;
            this.spitems = response.data.spitems;
            this.totalItemsLen = this.sellform.items.length + this.spitems.length;
            this.spitems.forEach(item => {
              hthis.totalPackitemLen += item.sellitems.length;
              hthis.mergeSpitems = hthis.mergeSpitems.concat(item.sellitems);
            })
            this.getRooms();
            // this.getOrg();

            this.$nextTick(function () {
                this.sellform.items.forEach((item, index) => {
                  this.replaceSpec(item, index);
                });
                this.getMutilHouse();
              }
            )
            this.picktype = this.sellform.quitSRType;
            this.strmid = response.data.saleform.storermguid;
            this.dict = response.data.dict;
            this.orgguid = this.sellform.storerOrgguid;


            let wxParams = response.data.params;
            //配置微信公众号参数
            this.wxConfig(response.data.params);
            //上传
            this.wxUoloadImage(that);
          } else {
            this.toastError('系统错误：' + response.data.msg);
          }
        });
      },
      /**
       * 获取扣杂方式，扣杂率
       * @param id
       * @param that
       */
      getDiscountRate: function(id, that) {
        this.axios({
          method: 'post',
          url: '/sales/Whoutform!getDiscountRate.action',
          params: {quitSRType: sellform.quitSRType, orderid: id, url: location.href.split("#")[0]}
        }).then(response => {
          if (response.data.result == "success") {
            this.discountRate = response.data.discountRate;
          } else {
            this.toastError('系统错误：' + response.data.msg);
          }
        });
      },
      getRefuseNodes: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Flowtempnode!getRefuseNodes.action',
          params: {orderid: this.id, nodeid: this.nodeid}
        }).then(response => {

          if (response.data.msg == 'success') {
            this.refuseNodes = response.data.optNodes.map(function (item) {
              return {text: item.name,
                onClick: function() {
                  $.confirm("确定要将订单回退到 " + item.name + " 节点？", function() {
                    that.doReject(item.guid, item.name, item.operatorid);
                  })
                }};
            });
          } else {
            this.toastText('获取可回退节点数据失败!');
          }
        });
      },
      rejectIt: function () {
        if (!this.checkEmy('opinion')) {
          this.toastText('意见不能为空！');
          return false;
        }
        if (this.refuseNodes.length > 0) {
          $.actions({
            title: '选择回退节点',
            actions: this.refuseNodes
          });
        } else {
          this.toastText('无可回退节点！');
          return false;
        }
      },
      doReject: function (refuseNodeid, refuseNodename, refuseOperatorid) {
        let that = this;

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        // postData.imgids = this.images.serverId.join(',');
        postData.imgids = '';
        postData.sellformid = this.id;
        postData.opinion = ($('#opinion').val() || '') + ' 退回到' + refuseNodename;
        postData.nodeid = this.nodeid;
        postData.refuseNodeid = refuseNodeid;
        postData.backUserid = refuseOperatorid;
        this.axios({
          method: 'post',
          url: '/sales/Sellform!refuse.action',
          data: qs.stringify(postData)
        }).then((response) => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            this.toastSuccess('提交成功!');
            this.$router.push({name: 'Sellform'});
          } else if (response.data.msg == 'canotRefuse') {
            this.toastText('不允许拒绝，需删除子订单！');
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
          //不不设置提示
        } else {
          this.toastError('系统错误');
        }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      postForm: function () {
        let that = this;

        if (!this.checkNull(this.sellform.orgName)) {
          this.toastText('库存组织为空，不能出库！');
          return false;
        } else if (!this.checkEmy('houseroom')) {
          this.toastText('货品明细库间有误！');
          return false;
        }
          if (!this.checkEmy('outcount')) {
            this.toastText('货品明细出库件数有误！');
            return false;
          } else if (!this.checkEmy('weight')) {
            this.toastText('货品明细净重有误！');
            return false;
          }
        if (this.annex.indexOf('whout') > -1) {
          if (this.images1.serverId.length == 0) {
            this.toastText('请上传出库单！');
            return false;
          }
        }

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        postData = this.serialize2Obj($("#formid").serializeArray());
        postData.whoutformIds = this.images1.serverId.join(',');
        postData.orderid = this.id;
        postData.nodeid = this.nodeid;
        //postData.status = this.status;
        postData.opttype = 2;
        postData['entity.orgname'] = this.orgname;
        this.axios({
          headers: {
            'artoken': this.artoken,
          },
          method: 'post',
          url: '/sales/Whoutform!doSaleOutForm.action',
          data: qs.stringify(postData)
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'repeatSubmit') {
            this.toastText('重复提交');
          } else if (response.data.msg == 'success') {
            this.toastSuccess('出库成功!');
            this.$router.push({name: 'Sellform', query:{stat: this.status}});
          }
          // else if (response.data.msg == 'checkError') {
          //   this.toastText3('明细重量必须等于整车重量');
          // }
          else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作');
            this.artoken = this.createToken();
          } else if (response.data.msg == 'nowhinfo') {
            this.toastText('库存不足！');
          } else if (response.data.msg == 'error') {
            this.toastText('系统错误');
            this.artoken = this.createToken();
          } else if (response.data.msg) {
            this.toastText3(response.data.msg);
            this.artoken = this.createToken();
          } else {
            this.toastError('系统错误');
            this.artoken = this.createToken();
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });

      },
      openLogs: function() {
        this.$router.push({name: 'SalesOperationLogs2', query: {orderid: this.id, srguid: this.sellform.storermguid, departid: this.sellform.depguid}});
      }
    }
  }
</script>
